import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import Params from '../components/goods/Params.vue'
import Survey from '../components/survey/Survey.vue'
import SurveyDetail from '../components/survey/SurveyDetail.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/survey', component: Survey, meta: { title: '问卷调查系统' } },
  {
    path: '/surveyDetail/:userId',
    component: SurveyDetail,
    name: 'surveydetail',
    meta: { title: '问卷调查系统' }
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂在前置导航守卫来守卫只有带token的请求才能访问其他页面，否则就只能访问login页面
router.beforeEach((to, from, next) => {
  // to表示将要访问的路由
  // from代表从那个路由跳转而来
  // next 是一个函数，表示放行
  if (to.path === '/login') {
    return next()
  }
  // 获取token
  const token = window.sessionStorage.getItem('token')
  if (!token) {
    return next('/login')
  } // 没有token就强制跳转回登录页面
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next() // 有token就放行
})

export default router
